package com.clwl.supervise.superviseapp.service.inspect;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ContentList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ItemList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.*;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.SequenceService;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.liability.LiabilityService;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.HolidayUtil;
import com.clwl.supervise.superviseapp.util.RedisUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Year;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DailyInspectV2Service {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private BaseDataService baseDataService;


    @Resource
    private TcCompanyMapper companyMapper;
    @Resource
    private JgTemplateMapper templateMapper;
    @Resource
    private JgProcessCodeMapper processCodeMapper;
    @Resource
    private JgDailyStandardMapper jgDailyStandardMapper;
    @Resource
    private JgDailyContentMapper jgDailyContentMapper;
    @Resource
    private JgCheckContentMapper jgCheckContentMapper;
    @Resource
    private JgCheckMissingMapper jgCheckMissingMapper;
    @Resource
    private JgCheckProblemMapper jgCheckProblemMapper;
    @Resource
    private TsDeptMapper deptMapper;
    @Resource
    private TsUserMapper userMapper;
    @Resource
    private JgFlightPlanCheckMapper flightPlanCheckMapper;
    @Resource
    private JgSchemePlanCheckMapper schemePlanCheckMapper;
    @Resource
    private JgDailyCheckMapper dailyCheckMapper;
    @Resource
    private JgRectificationMapper rectificationMapper;
    @Resource
    private JgRectificationContentMapper rectificationContentMapper;
    @Resource
    private JgInvestigationContentMapper investigationContentMapper;
    @Resource
    private JgInvestigationMapper investigationMapper;
    @Resource
    private JgStandardMapper jgStandardMapper;
    @Resource
    private JgCheckInformMapper jgCheckInformMapper;
    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;
    @Resource
    private JgInvestigationSetMapper jgInvestigationSetMapper;
    @Resource
    private JgDailyCheckSetMapper jgDailyCheckSetMapper;

    @Resource
    private JgScDynamicScoringMapper scDynamicScoringMapper;

    @Resource
    private JgUnplannedCompanyMapper jgUnplannedCompanyMapper;
    @Resource
    private TsDeptMapper tsDeptMapper;

    @Resource
    private JgClassifySpscCompMapper jgClassifySpscCompMapper;
    @Resource
    private JgClassifySpscMapper classifySpscMapper;
    @Resource
    private JgClassifyCyfwMapper classifyCyfwMapper;
    @Resource
    private JgClassifySpxsMapper classifySpxsMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private SequenceService sequenceService;

    @Resource
    private LiabilityService liabilityService;


    /**
     * 获取日常检查的企业列表(现在这里查询的只有经营的企业)
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */

    @Transactional(readOnly = true)
    public Page<Map<String, Object>> selectCompanyPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity, String processBathQueryEntity, String processBathQueryId, String processBathQueryCode) {
        String dataRange = UserHelper.getUserInfo().getDataRange();
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(dataRange);
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        commonSearchEntity.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            commonSearchEntity.setDataDeptId(dataDeptEntity.getId());
        } else {
            commonSearchEntity.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            commonSearchEntity.setIsSc("1");
        } else {
            commonSearchEntity.setIsSc("0");
        }

        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        // List processList = null;
        List codeList = null;
//        if(StringUtils.isNotEmpty(processBathQueryId)){
//            String[] processIdArr = processBathQueryId.split(",");
//            processList = Arrays.asList(processIdArr);
//        }
        if (StringUtils.isNotEmpty(processBathQueryCode)) {
            String[] codeArr = processBathQueryCode.split(",");
            codeList = Arrays.asList(codeArr);
        }
        List<String> processList = CompanyProcessUtil.getUserProcessList();
        commonSearchEntity.setProcessList(processList);

        List<String> holidayList = HolidayUtil.getYearHolidays(DateUtil.year(new Date()));
        if ("0".equals(commonSearchEntity.getType())) {
            List<ProcessBathQueryEntity> processBathQueryEntityList = processBathQueryEntity == null ? new ArrayList<>() : JSONArray.parseArray(processBathQueryEntity, ProcessBathQueryEntity.class);
            int currentYear = DateUtil.year(new Date());
            //总条数
            Long total = companyMapper.selectDailyInpectionCount(commonSearchEntity, processBathQueryEntityList, codeList, currentYear);
            iPage.setTotal(total);
            Page<Map<String, Object>> pageList = companyMapper.selectDailyInpectionPage(iPage, commonSearchEntity, processBathQueryEntityList, codeList, currentYear);
            // 获取运算结果是同步过程，即 call 方法执行完成，才能获取结果
            int year = DateUtil.year(new Date());
            for (Map<String, Object> record : pageList.getRecords()) {//resultThread.get().getRecords()) {
                List<Map<String, Object>> indexList = new ArrayList<>();
                String startTimeLimit = record.get("START_TIME_LIMIT") == null ? "" : record.get("START_TIME_LIMIT") + "";
                String checkIdLimit = record.get("CHECK_ID_LIMIT") == null ? "" : record.get("CHECK_ID_LIMIT") + "";
                String endTimeLimit = record.get("END_TIME_LIMIT") == null ? "" : record.get("END_TIME_LIMIT") + "";
                String checkIndexLimit = record.get("CHECK_INDEX_LIMIT") == null ? "" : record.get("CHECK_INDEX_LIMIT") + "";
                String checkStatusLimit = record.get("CHECK_STATUS_LIMIT") == null ? "" : record.get("CHECK_STATUS_LIMIT") + "";
                String delayCheckDateLimit = record.get("DELAY_CHECK_DATE_LIMIT") == null ? "" : record.get("DELAY_CHECK_DATE_LIMIT") + "";
                String supProcess = record.get("SUP_PROCESS") == null ? "" : record.get("SUP_PROCESS") + "";
                String riskLevel = record.get("RISK_LEVEL") == null ? "" : record.get("RISK_LEVEL") + "";
                String companyTypeId = record.get("COMPANY_TYPE_ID") == null ? "" : record.get("COMPANY_TYPE_ID") + "";
                if (StringUtils.equals(supProcess, "spxs") && StringUtils.equals(riskLevel, "A") && StringUtils.equalsAny(companyTypeId, "2", "5")) {
                    //参与双随机的企业 不生成日常检查次数
                    record.put("CHECK_LIST", indexList);
                    continue;
                }
                String[] checkIdArray = checkIdLimit.split(",");
                String[] startTimeArray = startTimeLimit.split(",");
                String[] endTimeArray = endTimeLimit.split(",");
                String[] checkIndexArray = checkIndexLimit.split(",");
                String[] checkStatusArray = checkStatusLimit.split(",");
                String[] delayCheckDateArray = delayCheckDateLimit.split(",");
                for (int i = 0; i < startTimeArray.length; i++) {
                    Map<String, Object> checkMap = new HashMap<>();
                    checkMap.put("CHECK_ID", checkIdArray[i]);
                    checkMap.put("CHECK_STATUS", checkStatusArray[i]);
                    checkMap.put("CHECK_INDEX", checkIndexArray[i]);
                    checkMap.put("CHECK_START_DATE", year + "-" + startTimeArray[i]);
                    checkMap.put("CHECK_END_DATE", StringUtils.equals(delayCheckDateArray[i], "0") ? year + "-" + endTimeArray[i] : delayCheckDateArray[i]);
                    //临期状态 日常检查10天前
                    String endDate = StringUtils.equals(delayCheckDateArray[i], "0") ? year + "-" + endTimeArray[i] : delayCheckDateArray[i];
                    //判断与当前日期相差天数
                    if (endDate.length() >= 10) {
                        long days = HolidayUtil.getLastYearWorkdayDays(new Date(), DateUtil.parse(endDate), holidayList);
                        if (days <= 10) {
                            checkMap.put("ADVENT_STATUS", "L");
                        } else {
                            checkMap.put("ADVENT_STATUS", "Z");
                        }
                    }
                    indexList.add(checkMap);
                }
                record.put("CHECK_LIST", indexList);
            }

            return iPage;

        } else {
            Long total = companyMapper.selectInspectionResultCount(commonSearchEntity);
            iPage.setTotal(total);
            Page<Map<String, Object>> page = companyMapper.selectInspectionResultPage(iPage, commonSearchEntity);
            return page;
        }

    }

    /**
     * 验证社会评分列表是否现实
     *
     * @param companyId
     * @return IS_LIABILITY :
     */
    public String getLiability(Long companyId, Long checkId) {
        TcCompany tcCompany = companyMapper.selectById(companyId);
        int count = dailyCheckMapper.queryLiabilityCount(companyId, "4");
        //1入网餐饮服务经营者，没有社会责任评分的，需要做1次社会责任评分
        //第一步：根据企业id查询社会责任评分表
        if ((count == 0 || StringUtils.isEmpty(tcCompany.getRiskLevel())) || checkId == null) {
            return "0";
        } else if ((count == 0 || StringUtils.isEmpty(tcCompany.getRiskLevel())) || checkId != null) {
            String status = dailyCheckMapper.queryDailyCheckStatusByCheckId(checkId);
            return !StringUtils.equals(status, "1") ? "0" : "1";
        } else {
            //2.已经有社会责任评分的，本年度风险等级与上一年度风险等级不一致时，进行一次社会责任评分。
            //获取年度的风险等级评定
            // 获取当前年份
            int currentYear = Year.now().getValue();
            // 减去一年
            int riskYear = currentYear - 1;
            String checkRiskLevel = dailyCheckMapper.queryRiskLevel(companyId, Integer.toString(riskYear));
            //尽量不碰原逻辑，此处增加查询生产企业的日常检查数据
            return StringUtils.equals(checkRiskLevel, tcCompany.getRiskLevel()) ? "1" : "0";//是否显示社会责任评分：0：显示，1：不显示
        }
    }

    /**
     * 日常检查的检查结果列表
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */

    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectInspectionResultPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        Long userId = UserHelper.getUserId();
        commonSearchEntity.setUserId(userId);
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        commonSearchEntity.setProcessList(processList);
        return companyMapper.selectInspectionResultPage(iPage, commonSearchEntity);
    }


    public Map<String, Object> selectCompanyInfo(Long checkId, Long companyId, Integer checkNum) {
        Map<String, Object> companyInfo = companyMapper.selectCompanyInspectionInfo(companyId);

        JgDailyCheck dailyCheck = null;
        if (checkId == null || checkId == 0) {
            //创建日常检查
            dailyCheck = getJgDailyCheck(companyId, checkNum);
        } else {
            dailyCheck = dailyCheckMapper.selectById(checkId);
        }

        companyInfo.put("CHECK_TIME", dailyCheck.getCheckTime());
        //经营状态;0正常，1异常
        companyInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus() == null ? "0" : dailyCheck.getManageStatus());
        companyInfo.put("COMANY_PIC", dailyCheck.getComanyPic());
        companyInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult() == null ? "符合" : dailyCheck.getCheckResult());
        companyInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem() == null ? "" : dailyCheck.getOtherProblem());
        companyInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults() == null ? "" : dailyCheck.getProcessResults());
        companyInfo.put("RECTIFY_TIME", dailyCheck.getRectificationTimeLimit() == null ? "" : dailyCheck.getRectificationTimeLimit());
        //获取主体异常信息
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), dailyCheck.getType());
        if (jsEntAnomaly != null) {
            companyInfo.put("ABNORMAL_CAUSE", jsEntAnomaly.getAbnormalCause());
            companyInfo.put("AUDIT_TRAILS", jsEntAnomaly.getAuditTrails());
        }
        log.info("companyInfo:{}", companyInfo);

        Long deptId = UserHelper.getUserInfo().getDeptId();
        TsDept dept = deptMapper.selectById(deptId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptName", dept.getName());
        if (dailyCheck != null) {
            resultMap.put("checkId", dailyCheck.getId());
            resultMap.put("checkItemTableUrl", dailyCheck.getCheckItemTableUrl());
            resultMap.put("resultRecordUrl", dailyCheck.getResultRecordUrl());
            resultMap.put("informUrl", dailyCheck.getInformUrl());
        }
        TcCompany company = companyMapper.selectById(companyId);
        //检查未完成的情况下检查人1显示当前登陆人，检查人2显示企业第二执法人。检查完成的情况下 直接显示之前保存的检查人信息
        resultMap.put("checkPerson1Id", !StringUtils.equals("1", dailyCheck.getCheckStat()) ? UserHelper.getUserId() : dailyCheck.getCheckPerson1Id());
        resultMap.put("checkPerson1Name", !StringUtils.equals("1", dailyCheck.getCheckStat()) ? UserHelper.getUserInfo().getName() : dailyCheck.getCheckPerson1Name());
        resultMap.put("checkPerson2Id", !StringUtils.equals("1", dailyCheck.getCheckStat()) ? company.getLegalHead2Id() : dailyCheck.getCheckPerson2Id());
        resultMap.put("checkPerson2Name", !StringUtils.equals("1", dailyCheck.getCheckStat()) ? company.getLegalHead2Name() : dailyCheck.getCheckPerson2Name());
        companyInfo.putAll(resultMap);
        return companyInfo;
    }


    public TcCompany selectCheckInfo(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        company.setLegalHead1Name(UserHelper.getUserInfo().getName());
        if (UserHelper.getUserId() == company.getLegalHead2Id()) {
            company.setLegalHead2Id(company.getLegalHead1Id());
        }
        //主体类别
        if (StringUtils.equals("cyfw", company.getSupProcess())) {
            JgClassifyCyfw classify = classifyCyfwMapper.selectById(company.getCompanyTypeId());
            company.setCompanyTypeName(classify == null ? "" : classify.getName());
        }
        if (StringUtils.equals("spxs", company.getSupProcess())) {
            JgClassifySpxs classify = classifySpxsMapper.selectById(company.getCompanyTypeId());
            company.setCompanyTypeName(classify == null ? "" : classify.getName());
        }
        if (StringUtils.equals("tssc", company.getSupProcess())) {
            List<JgClassifySpscComp> classifyList = jgClassifySpscCompMapper.selectList(new QueryWrapper<JgClassifySpscComp>().eq("company_id", companyId));
            if (classifyList.isEmpty()) {
                company.setCompanyTypeName("");
            } else {
                List<Long> classifyIds = classifyList.stream().map(JgClassifySpscComp::getClassifySpsc1Id).collect(Collectors.toList());
                List<JgClassifySpsc> classifySpscList = classifySpscMapper.selectBatchIds(classifyIds);
                if (!classifySpscList.isEmpty()) {
                    List<String> classifyNames = classifySpscList.stream().map(JgClassifySpsc::getName).collect(Collectors.toList());
                    company.setCompanyTypeName(String.join(",", classifyNames));
                }
            }
        }
        return company;
    }

    /**
     * 获取数据字典列表
     *
     * @return
     */
    public List<Map<String, Object>> getDictList() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        //查询静态分值评定-异常原因 数据字典
        List<SysDictData> dictDataList = sysDictDataMapper.selectByDictTypeCode("abnormal_reason_type");
        if (dictDataList != null && dictDataList.size() > 0) {
            for (SysDictData data : dictDataList) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", data.getDictLabel());
                map.put("text", data.getDictLabel());
                mapList.add(map);

            }
        }
        return mapList;
    }

    /**
     * 获取检查的基础信息中的监管单位信息
     */

    public List<Map<String, Object>> selectCheckItemList(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        if (!("spsc".equals(company.getSupProcess()) || "tssc".equals(company.getSupProcess())) && company.getCompanyTypeId() == null) {
            throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
        } else {
            List<JgClassifySpscComp> classifyList = jgClassifySpscCompMapper.selectList(new QueryWrapper<JgClassifySpscComp>().eq("company_id", companyId));
            if (classifyList.isEmpty()) {
                throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
            }
        }

        //风险信息
        Map<String, String> riskMap = baseDataService.riskInfo(companyId);
        List<String> riskCode = new ArrayList<>();
        Set<String> riskKeySet = riskMap.keySet();
        for (String riskKey : riskKeySet) {
            if (!"0".equals(riskMap.get(riskKey))) {
                riskCode.add(riskKey);
            }
        }

        String supProcess = company.getSupProcess();
        //查看当前企业是否之前填写了检查信息
        try {
            List<Map<String, Object>> checkMissingListAll = jgCheckMissingMapper.selectMapList();
            List<Map<String, Object>> checkProblemListAll = jgCheckProblemMapper.selectMapList();
            List<Map<String, Object>> checkStandardList = jgDailyStandardMapper.selectStandardList(supProcess, company.getCompanyTypeId(), null, "1");
            for (Map<String, Object> checkStandard : checkStandardList) {
                //获取标准中检查内容
                //log.info("已经存在的检查结果获取历史检查数据,TEPLATE_STANDARD_ID:{},DAILT_STANDARD_ID:{}", checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"));
                List<Map<String, Object>> contentList = jgDailyContentMapper.selectByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"), riskCode);
                for (Map<String, Object> content : contentList) {
                    //获取content的检查说明选项
                    List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    //                      jgCheckMissingMapper.selectByContentId(content.get("ID"));
                    content.put("checkMissingList", checkMissingList);
                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    //jgCheckProblemMapper.selectByContentId(content.get("ID"));
                    //写死输入框
                    content.put("PROBLEM_PRE_TYPE", content.get("PROBLEM_PRE_TYPE"));
                    //                        content.put("PROBLEM_CONTENT","自定义备注");
                    if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                        //多选的情况下处理
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (content.get("PROBLEM_CONTENT") != null) {
                                String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    content.put("checkProblemList", checkProblemList);
                }
                checkStandard.put("contentList", contentList);
            }
            return checkStandardList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取检查信息失败!");
        }
    }

    public List<Map<String, Object>> selectLiabilityItem(Long checkId, Long dynamicScoringId, Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        List<Map<String, Object>> checkStandardList = jgDailyStandardMapper.selectLiabilityStandardList(company.getSupProcess(), company.getCompanyTypeId(), checkId, dynamicScoringId, "4");
        //风险信息
        if (checkId == null && dynamicScoringId == null) {
            for (Map<String, Object> checkStandard : checkStandardList) {
                //获取标准中检查内容
                //log.info("已经存在的检查结果获取历史检查数据,TEPLATE_STANDARD_ID:{},DAILT_STANDARD_ID:{}", checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"));
                List<Map<String, Object>> contentList = jgDailyContentMapper.selectByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"), null);
                for (Map<String, Object> content : contentList) {
                    //获取content的检查说明选项
                    List<Map<String, Object>> checkMissingList = jgCheckMissingMapper.selectByContentId(content.get("ID"));
                    content.put("checkMissingList", checkMissingList);
                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = jgCheckProblemMapper.selectByContentId(content.get("ID"));
                    if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                        //多选的情况下处理
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (content.get("PROBLEM_CONTENT") != null) {
                                String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    content.put("checkProblemList", checkProblemList);
                }
                checkStandard.put("contentList", contentList);
            }
            return checkStandardList;
        } else {
            //标准列表
            for (Map<String, Object> checkStandard : checkStandardList) {
                //获取标准中检查内容
                // log.info("已经存在的检查结果获取历史检查数据,TEPLATE_STANDARD_ID:{},DAILT_STANDARD_ID:{}", checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"));
                Object dailtStandardId = checkStandard.get("DAILT_STANDARD_ID");

                List<Map<String, Object>> contentList = jgDailyContentMapper.selectLiabilityStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), dailtStandardId);
                for (Map<String, Object> content : contentList) {
                    if (content.get("SELECTION") != null) {
                        content.put("SELECTION", Integer.parseInt(content.get("SELECTION").toString()));
                    }

                    //获取content的检查说明选项
                    List<Map<String, Object>> checkMissingList = jgCheckMissingMapper.selectByContentId(content.get("ID"));
                    content.put("checkMissingList", checkMissingList);
                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = jgCheckProblemMapper.selectByContentId(content.get("ID"));
                    if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                        //多选的情况下处理
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (content.get("PROBLEM_CONTENT") != null) {
                                String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    content.put("checkProblemList", checkProblemList);
                }
                checkStandard.put("contentList", contentList);
            }
            return checkStandardList;
        }

    }

    /**
     * 获取日常检查信息,没有就创建一个
     *
     * @param companyId
     * @param checkNum  是null 代表是临时的非计划
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck getJgDailyCheck(Long companyId, Integer checkNum) {
        //创建一个
        if (checkNum == null || checkNum == 0) { //非计划检查
            //获取是否存在为完成的临时的非计划,如果是非临时的非计划应该是存在checkId的所以到不了这里
            JgDailyCheck dailyCheck = dailyCheckMapper.selectNoRealyTempUnplanned(companyId, DateUtil.format(new Date(), "yyyy"));
            if (dailyCheck != null) {
                dailyCheck.setCheckPerson1Id(dailyCheck.getCheckPerson1Id() == null ? UserHelper.getUserId() : dailyCheck.getCheckPerson1Id());
                dailyCheck.setCheckPerson1Name(dailyCheck.getCheckPerson1Name() == null ? UserHelper.getUserInfo().getName() : dailyCheck.getCheckPerson1Name());
                if (dailyCheck.getCheckPerson2Id() == null) {
                    List<TsUser> selectSuperviseList = baseDataService.getSupervisePersonList();
                    //排除checkPerson2Id
                    JgDailyCheck finalDailyCheck = dailyCheck;
                    selectSuperviseList = selectSuperviseList.stream().filter(user -> {
                        return user.getId() != finalDailyCheck.getCheckPerson1Id();
                    }).collect(Collectors.toList());
                    if (selectSuperviseList.size() > 0) {
                        dailyCheck.setCheckPerson2Id(selectSuperviseList.get(0).getId());
                        dailyCheck.setCheckPerson2Name(selectSuperviseList.get(0).getName());
                    }
                }
                return dailyCheck;
            } else {
                TcCompany company = companyMapper.selectById(companyId);
                //创建非计划单子
                dailyCheck = createDailyCheck(company, 0, true);
                dailyCheck.setCheckPerson2Id(company.getLegalHead2Id());
                dailyCheck.setCheckPerson2Name(company.getLegalHead2Name());
                dailyCheck.setCheckPerson1Id(company.getLegalHead1Id());
                dailyCheck.setCheckPerson1Name(company.getLegalHead1Name());
                return dailyCheck;
            }
        } else { //日常检查
            //查看确认是否没有历史检查信息
            JgDailyCheck dailyCheck = dailyCheckMapper.selectDailyCheck(companyId, DateUtil.year(new Date()), checkNum);
            if (dailyCheck == null) {
                //创建日检查单子
                TcCompany company = companyMapper.selectById(companyId);
                dailyCheck = createDailyCheck(company, checkNum, false);
                return dailyCheck;
            } else {
                //如果重复了 删除多余i的
                Long userId = dailyCheck.getCheckPerson1Id() == null ? UserHelper.getUserId() : dailyCheck.getCheckPerson1Id();
                dailyCheck.setCheckPerson1Id(userId);
                TsUser user = userMapper.selectById(userId);
                dailyCheck.setCheckPerson1Name(user.getName());
                return dailyCheck;
            }
        }
    }

    /**
     * @param company
     * @param checkNum
     * @param isUnplanned
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck createDailyCheck(TcCompany company, Integer checkNum, boolean isUnplanned) {
        int currentDate = DateUtil.year(new Date());
        String supProcess = company.getSupProcess();
        //通过同步的方式防止创建两个相同的检查数据

        JgTemplate template = templateMapper.selectBySupProcess(supProcess, company.getCompanyTypeId(), "1");
        //添加社会评分评分
        JgTemplate shTemplate = templateMapper.selectBySupProcess(company.getSupProcess(), company.getCompanyTypeId(), "4");
        if (template == null) {
            throw new RuntimeException("检查模板为空");
        }
        TsDept dept = null;
        if (UserHelper.getUserInfo().getDeptId() != null) {
            dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
        }
        String syncKey = company.getId() + "_" + checkNum + "_" + isUnplanned;
        synchronized ((syncKey).intern()) {
            JgDailyCheck dailyCheck = null;
            if (isUnplanned) {
                //非计划
                dailyCheck = dailyCheckMapper.selectNoRealyTempUnplanned(company.getId(), currentDate + "");
            } else {
                dailyCheck = dailyCheckMapper.selectDailyCheck(company.getId(), currentDate, checkNum);
            }
            if (dailyCheck == null) {
                dailyCheck = new JgDailyCheck();
            }
            if (isUnplanned) {
                dailyCheck.setIsUnplanned("1");
                dailyCheck.setIsTempUnplanned("1");
            } else {
                dailyCheck.setIsUnplanned("0");
                dailyCheck.setIsTempUnplanned("0");
            }
            dailyCheck.setTemplateId(template.getId());
            //新增：社会检查模版Id
            if (shTemplate != null) {
                dailyCheck.setLiabilityTemplateId(shTemplate.getId());
            }

            dailyCheck.setTemplateName(template == null ? "" : template.getName());
            dailyCheck.setDeptId(UserHelper.getUserInfo().getDeptId());
            if (dept != null) {
                dailyCheck.setDeptName(dept.getName());
                dailyCheck.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                dailyCheck.setCreateDeptName(dept.getName());
            }
            dailyCheck.setCompanyId(company.getId());
            dailyCheck.setCompanyName(company.getCompanyName());
            dailyCheck.setCreditCode(company.getCreditCode());
            dailyCheck.setLicense(company.getLicense());
            dailyCheck.setComanyPic(company.getComanyPic());
            dailyCheck.setComanyThumbnail(company.getComanyThumbnail());
            dailyCheck.setCheckNum(Long.valueOf(checkNum));
            dailyCheck.setCheckYear(Long.valueOf(DateUtil.format(new Date(), "yyyy")));
            dailyCheck.setCheckStat("3");
            dailyCheck.setCreateTime(new Date());
            dailyCheck.setCreatorId(UserHelper.getUserId());
            dailyCheck.setCreator(UserHelper.getUserInfo().getName());
            dailyCheck.setDeleteFlag(0L);
            dailyCheck.setType("1");
            //默认是当前登陆人
            dailyCheck.setCheckPerson1Id(UserHelper.getUserId());
            dailyCheck.setCheckPerson1Name(UserHelper.getUserInfo().getName());
            //再次确认是否已经存在
            JgDailyCheck dailyCheckQ = dailyCheckMapper.selectDailyCheck(company.getId(), currentDate, checkNum);
            if (dailyCheck.getId() == null || dailyCheckQ == null) {
                dailyCheckMapper.insert(dailyCheck);
            } else {
                dailyCheckMapper.updateById(dailyCheck);
            }
            return dailyCheck;
        }
    }

    /**
     * 保存检查项结果内容
     *
     * @param standardId              检查标准id
     * @param contentId               检查内容Id
     * @param result                  选择的结果
     * @param problemContent          问题描述
     * @param checkExplain            检查说明
     * @param problemContentInput     问题描述输入的内容
     * @param missingItemContentInput 检查说明输入的内容
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCheckItem(Long checkId, Long standardId, Long contentId, String result, String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput) {
        //用redis保证数据请求唯一性
        // if(redisUtil.get(checkId+UserHelper.getUserId()+contentId+"rc") != null){
        //     throw new RuntimeException("操作的太快啦!");
        // }
        //redisUtil.set(checkId+UserHelper.getUserId()+contentId+"rc",result,1l);
        ////检查是否已经存在日常检查的信息
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());

        TsDept dept = null;
        if (UserHelper.getUserInfo().getDeptId() != null) {
            dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
        }

        //获取有没有此项的DailyStandard
        JgDailyStandard dailyStandard = jgDailyStandardMapper.selectStandard(standardId, dailyCheck.getId());
        JgStandard jgStandard = jgStandardMapper.selectById(standardId);
        if (dailyStandard == null) {
            //创建保存的标准信息
            dailyStandard = new JgDailyStandard();
            dailyStandard.setTemplateId(dailyCheck.getTemplateId());
            dailyStandard.setStandardId(standardId);
            dailyStandard.setSupCategory("1");
            dailyStandard.setSupProcess(company.getSupProcess());
            dailyStandard.setSpxsId(jgStandard.getSpxsId());
            dailyStandard.setCyfwId(jgStandard.getCyfwId());
            dailyStandard.setSpscLbId(jgStandard.getSpscLbId());
            dailyStandard.setSpscLbZlId(jgStandard.getSpscLbZlId());
            dailyStandard.setTsspLbId(jgStandard.getTsspLbId());
            dailyStandard.setTsspLbZlId(jgStandard.getTsspLbZlId());
            dailyStandard.setName(jgStandard.getName());
            dailyStandard.setSerialNum(jgStandard.getSerialNum());
            dailyStandard.setDailyCheckId(dailyCheck.getId());
            dailyStandard.setCreateTime(new Date());
            dailyStandard.setCreatorId(UserHelper.getUserId());
            dailyStandard.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyStandard.setCreateDeptName(dept.getName());
                dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            }
            dailyStandard.setDeleteFlag(0L);
            jgDailyStandardMapper.insert(dailyStandard);
        }
        //获取此项检查内容是否已经填写过
        JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(contentId, dailyStandard.getId(), new ArrayList<>());

        JgCheckContent content = jgCheckContentMapper.selectById(contentId);
        if (dailyContent == null) {
            dailyContent = new JgDailyContent();
            dailyContent.setContentId(contentId);
            dailyContent.setDailyStandardId(dailyStandard.getId());
            dailyContent.setCreateTime(new Date());
            dailyContent.setCreatorId(UserHelper.getUserId());
            dailyContent.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyContent.setCreateDeptId(dept.getId());
                dailyContent.setCreateDeptName(dept.getName());
            }
            dailyContent.setDeleteFlag(0L);
            dailyContent.setCheckContent(content.getCheckContent());
            dailyContent.setImportentItem(content.getImportentItem());
            dailyContent.setSerialNum(content.getSerialNum());
            dailyContent.setMissingItem(content.getMissingItem());
            dailyContent.setRemark(content.getRemark());
        }
        if ("1".equals(result)) {
            dailyContent.setScore(content.getYesScore());
        } else {
            dailyContent.setScore(content.getScore());
        }
        dailyContent.setSelection(result);
        dailyContent.setMissingItemContent(checkExplain);
        dailyContent.setProblemContent(problemContent);
        dailyContent.setProblemContentInput(problemContentInput);
        dailyContent.setMissingItemContentInput(missingItemContentInput);
        dailyContent.setMissingItemContent(checkExplain);
        if (dailyContent.getId() == null) {
            jgDailyContentMapper.insert(dailyContent);
        } else {
            jgDailyContentMapper.updateById(dailyContent);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    //保存社会责任评分 暂时不用
    public void saveLiability(Long checkId, Long standardId, Long contentId, String result, String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput) {
        //用redis保证数据请求唯一性
        // if(redisUtil.get(checkId+UserHelper.getUserId()+contentId+"rc") != null){
        //     throw new RuntimeException("操作的太快啦!");
        // }
        //redisUtil.set(checkId+UserHelper.getUserId()+contentId+"rc",result,1l);
        ////检查是否已经存在日常检查的信息
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());

        TsDept dept = null;
        if (UserHelper.getUserInfo().getDeptId() != null) {
            dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
        }

        //获取有没有此项的DailyStandard
        JgDailyStandard dailyStandard = jgDailyStandardMapper.selectStandard(standardId, dailyCheck.getId());
        JgStandard jgStandard = jgStandardMapper.selectById(standardId);
        if (dailyStandard == null) {
            //创建保存的标准信息
            dailyStandard = new JgDailyStandard();
            dailyStandard.setTemplateId(dailyCheck.getTemplateId());
            dailyStandard.setStandardId(standardId);
            dailyStandard.setSupCategory("4");
            dailyStandard.setSupProcess(company.getSupProcess());
            dailyStandard.setSpxsId(jgStandard.getSpxsId());
            dailyStandard.setCyfwId(jgStandard.getCyfwId());
            dailyStandard.setSpscLbId(jgStandard.getSpscLbId());
            dailyStandard.setSpscLbZlId(jgStandard.getSpscLbZlId());
            dailyStandard.setTsspLbId(jgStandard.getTsspLbId());
            dailyStandard.setTsspLbZlId(jgStandard.getTsspLbZlId());
            dailyStandard.setName(jgStandard.getName());
            dailyStandard.setSerialNum(jgStandard.getSerialNum());
            dailyStandard.setDailyCheckId(dailyCheck.getId());
            dailyStandard.setCreateTime(new Date());
            dailyStandard.setCreatorId(UserHelper.getUserId());
            dailyStandard.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyStandard.setCreateDeptName(dept.getName());
                dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            }
            dailyStandard.setDeleteFlag(0L);
            jgDailyStandardMapper.insert(dailyStandard);
        }
        //获取此项检查内容是否已经填写过
        JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(contentId, dailyStandard.getId(), new ArrayList<>());

        JgCheckContent content = jgCheckContentMapper.selectById(contentId);
        if (dailyContent == null) {
            dailyContent = new JgDailyContent();
            dailyContent.setContentId(contentId);
            dailyContent.setDailyStandardId(dailyStandard.getId());
            dailyContent.setCreateTime(new Date());
            dailyContent.setCreatorId(UserHelper.getUserId());
            dailyContent.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyContent.setCreateDeptId(dept.getId());
                dailyContent.setCreateDeptName(dept.getName());
            }
            dailyContent.setDeleteFlag(0L);
            dailyContent.setCheckContent(content.getCheckContent());
            dailyContent.setImportentItem(content.getImportentItem());
            dailyContent.setSerialNum(content.getSerialNum());
            dailyContent.setMissingItem(content.getMissingItem());
            dailyContent.setRemark(content.getRemark());
        }
        if ("1".equals(result)) {
            dailyContent.setScore(content.getYesScore());
        } else {
            dailyContent.setScore(content.getScore());
        }
        dailyContent.setSelection(result);
        dailyContent.setMissingItemContent(checkExplain);
        dailyContent.setProblemContent(problemContent);
        dailyContent.setProblemContentInput(problemContentInput);
        dailyContent.setMissingItemContentInput(missingItemContentInput);
        dailyContent.setMissingItemContent(checkExplain);
        if (dailyContent.getId() == null) {
            jgDailyContentMapper.insert(dailyContent);
        } else {
            jgDailyContentMapper.updateById(dailyContent);
        }
    }


    /**
     * 上传门头照
     *
     * @param checkId 检查Id
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck uploadCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.inspect.getPath());
        dailyCheck.setComanyPic(fileEntity.getFilePath());
        dailyCheck.setComanyThumbnail(fileEntity.getFileThPath());
        dailyCheckMapper.updateById(dailyCheck);
        return dailyCheck;
    }

    /**
     * 上传检查项的问题照片
     *
     * @param checkId    检查Id
     * @param standardId 检查标准id
     * @param contentId  检查内容Id
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String uploadItemFile(Long checkId, Long standardId, Long contentId, MultipartFile file) {
        try {
            JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
            JgDailyStandard dailyStandard = jgDailyStandardMapper.selectStandard(standardId, dailyCheck.getId());
            JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(contentId, dailyStandard.getId(), new ArrayList<>());
            dailyContent.setProblemFile(FileUploadUtil.uploadFile(file, FileUploadEnum.inspect.getPath()).getFilePath());
            jgDailyContentMapper.updateById(dailyContent);
            return dailyContent.getProblemFile();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败!");
        }

    }


    /**
     * 保存检查项结果内容（）
     *
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck saveCheckInfo(DailySaveVo dailySaveVo, boolean isMerge) {
        RectificationSituationData rectificationSituationData = JSONObject.parseObject(dailySaveVo.getRectificationSituationData(), RectificationSituationData.class);
        RectificationSituationData liabilitySituationData = JSONObject.parseObject(dailySaveVo.getLiabilitySituationData(), RectificationSituationData.class);
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(dailySaveVo.getCheckId());
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        if ("2".equals(dailySaveVo.getTemporary()) || StringUtils.equals(dailySaveVo.getManageStatus(), "1")) {
            //正式保存或者选择的经营异常 直接保存成完成
            dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            dailyCheck.setCheckStat("1");
        } else {
            dailyCheck.setCheckStat("3");
        }
        if (StringUtils.isNotBlank(dailySaveVo.getSuperviseOne()) && !"undefined".equals(dailySaveVo.getSuperviseOne())) {
            dailyCheck.setCheckPerson1Id(Long.parseLong(dailySaveVo.getSuperviseOne()));
            TsUser user = userMapper.selectById(Long.parseLong(dailySaveVo.getSuperviseOne()));
            dailyCheck.setCheckPerson1Name(user.getName());
        }
        if (StringUtils.isNotBlank(dailySaveVo.getSuperviseTwo()) && !"undefined".equals(dailySaveVo.getSuperviseTwo())) {
            dailyCheck.setCheckPerson2Id(Long.parseLong(dailySaveVo.getSuperviseTwo()));
            TsUser user = userMapper.selectById(Long.parseLong(dailySaveVo.getSuperviseTwo()));
            dailyCheck.setCheckPerson2Name(user.getName());
        }

        dailyCheck.setCheckResult(dailySaveVo.getCheckResults());
        dailyCheck.setManageStatus(dailySaveVo.getManageStatus());
        if (StringUtils.isNotBlank(dailySaveVo.getRectificationTimeLimit())) {
            dailyCheck.setRectificationTimeLimit(dailySaveVo.getRectificationTimeLimit());
        }

        if ("1".equals(dailySaveVo.getManageStatus())) {
            //如果选择的是异常的话
            dailySaveVo.setProcessResults("2");
        }
        dailyCheck.setProcessResults(dailySaveVo.getProcessResults());
        dailyCheck.setOtherProblem(dailySaveVo.getOtherProblem());


        saveItemListAndContentList(rectificationSituationData, dailyCheck, company, dailySaveVo.getManageStatus());

        //保存社会检查
        if (liabilitySituationData != null) {
            liabilityService.saveStandardInfo(liabilitySituationData, dailyCheck, company, dailySaveVo);
        }

        if (StringUtils.isNotEmpty(dailySaveVo.getTaskIds())) {
            //合并任务保存
            String[] taskArray = dailySaveVo.getTaskIds().split(",");
            for (String hCheckId : taskArray) {
                if (StringUtils.isEmpty(hCheckId)) {
                    continue;
                }
                dailySaveVo.setCheckId(Long.parseLong(hCheckId));
                saveCheckInfo(dailySaveVo, true);
            }
        }

        if (StringUtils.equals(dailySaveVo.getManageStatus(), "1")) {
            dailyCheckMapper.updateById(dailyCheck);
            //经营异常直接保存
            finaSaveInfo(dailySaveVo, false);
        } else {
            dailyCheckMapper.updateById(dailyCheck);
        }
        return dailyCheck;
    }


    /**
     * 最终保存
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck finaSaveInfo(DailySaveVo dailySaveVo, boolean isMerge) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(dailySaveVo.getCheckId());
        dailyCheck.setCheckStat("1");
        dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        dailyCheckMapper.updateById(dailyCheck);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        boolean companyTrue = false;
        if (StringUtils.isNotEmpty(dailySaveVo.getContactPhone())) {
            companyTrue = true;
            company.setContactPhone(dailySaveVo.getContactPhone());
        }
        if (StringUtils.isNotEmpty(dailySaveVo.getDoorHeadName())) {
            companyTrue = true;
            company.setDoorHeadName(dailySaveVo.getDoorHeadName());
        }
        if (StringUtils.isNotEmpty(dailySaveVo.getSignName())) {
            companyTrue = true;
            company.setSignName(dailySaveVo.getSignName());
        }
        if (StringUtils.isNotEmpty(dailySaveVo.getLegalPerson())) {
            companyTrue = true;
            company.setLegalPerson(dailySaveVo.getLegalPerson());
        }
        if (companyTrue) {
            companyMapper.updateById(company);
        }


        //如果选择的不是通过的话并且保存的不是合并的任务则生成相应的后续的整改和调查信息
        if ("2".equals(dailySaveVo.getProcessResults()) && !isMerge) {
            //责令整改
            saveRectification(dailySaveVo.getRectificationTimeLimit(), company, dailyCheck);
        } else if ("3".equals(dailySaveVo.getProcessResults()) && !isMerge) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification(dailySaveVo.getRectificationTimeLimit(), company, dailyCheck);
            //调查处理,查看调查处理开关是否打开
            JgInvestigationSet investigationSet = jgInvestigationSetMapper.selectByCheckTypeAndProcess(("6").equals(dailyCheck.getType()) ? "3" : "1", company.getSupProcess());
            //调查处理开关打开的情况下才生成下面的内容
            if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                saveInvestigation(company, dailyCheck);

            }
        }

        //如果保存的不是被合并的任务则更新动态评分信息
        if (!isMerge) {
            //保存最新数据到评级的分数表，每年评级的时候要用
            List<Map<String, Object>> dailyContentList = jgDailyContentMapper.selectByDailyCheckId(dailySaveVo.getCheckId());
            List<JgScDynamicScoring> jgScDynamicScoringList = scDynamicScoringMapper.selectByCompanyId(dailyCheck.getCompanyId());
            if (!dailyContentList.isEmpty()) {
                // 预构建 existingRecords 的映射（contentId → JgScDynamicScoring）
                Map<Long, JgScDynamicScoring> existingRecordMap = jgScDynamicScoringList.stream()
                        .collect(Collectors.toMap(
                                JgScDynamicScoring::getContentId,
                                Function.identity()
                        ));

                // 收集需要插入和更新的对象
                List<JgScDynamicScoring> insertList = new ArrayList<>();
                List<JgScDynamicScoring> updateList = new ArrayList<>();
                try {
                    for (Map<String, Object> dailyContentMap : dailyContentList) {
                        Long contentId = Long.parseLong(dailyContentMap.get("CONTENT_ID").toString());
                        JgScDynamicScoring record;

                        if (!existingRecordMap.containsKey(contentId)) {
                            // 创建新对象
                            record = new JgScDynamicScoring();
                            record.setContentId(contentId);
                            record.setCompanyId(dailyCheck.getCompanyId());
                            record.setCreateTime(new Date());
                            record.setCreatorId(UserHelper.getUserId());
                            record.setCreatorName(UserHelper.getUserInfo().getName());
                            record.setDeleteFlag("0");
//                        insertList.add(record);
                            scDynamicScoringMapper.insert(record);
                        } else {
                            // 获取已有对象
                            record = existingRecordMap.get(contentId);
                            record.setUpdateTime(new Date());
                            record.setUpdateName(UserHelper.getUserInfo().getName());
                            record.setUpdateId(UserHelper.getUserId());
                            updateList.add(record);
                        }

                        // 公共字段设置（无论新增还是更新）
                        record.setCheckContent(dailyContentMap.get("CHECK_CONTENT").toString());
                        record.setSelection(dailyContentMap.get("SELECTION").toString());
                        record.setScore(dailyContentMap.get("SCORE") != null ?
                                Double.parseDouble(dailyContentMap.get("SCORE").toString()) : 0.0);
                    }
                } catch (DuplicateKeyException e) {
                    e.printStackTrace();
                    log.info("+++++++++++++++++插入动态评分有重复记录+++++++++++++++");
                }


                // 批量操作
//                if (!insertList.isEmpty()) {
//                    scDynamicScoringMapper.batchInsert(insertList);  // 批量插入
//                }
                if (!updateList.isEmpty()) {
                    scDynamicScoringMapper.batchUpdate(updateList);   // 批量更新
                }
            }
        }


        if ("1".equals(dailyCheck.getManageStatus())) {
            //保存异常信息
            JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "1");
            if (jsEntAnomaly == null) {
                jsEntAnomaly = new JsEntAnomaly();
            }
            jsEntAnomaly.setCheckType("1");
            jsEntAnomaly.setCompanyId(company.getId());
            jsEntAnomaly.setCompanyName(company.getCompanyName());
            jsEntAnomaly.setCreditCode(company.getCreditCode());
            jsEntAnomaly.setLicense(company.getLicense());
            jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
            jsEntAnomaly.setAbnormalCause(dailyCheck.getAbnormalCause());
            jsEntAnomaly.setAuditTrails(dailySaveVo.getAuditTrails());
//            jsEntAnomaly.setRectifyTime(dailySaveVo.getRectifyTime());
            jsEntAnomaly.setCheckResults(dailySaveVo.getCheckResults());
            jsEntAnomaly.setProcessResults(dailySaveVo.getProcessResults());
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
            jsEntAnomaly.setCheckNumber(dailyCheck.getCheckNum() == null ? 1 : Integer.parseInt(dailyCheck.getCheckNum() + ""));
            if (jsEntAnomaly.getId() == null) {
                jsEntAnomaly.setCreateTime(new Date());
                jsEntAnomaly.setCreatorId(UserHelper.getUserId());
                jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());

                jsEntAnomalyMapper.insert(jsEntAnomaly);
            } else {
                jsEntAnomalyMapper.updateById(jsEntAnomaly);
            }
        }

        if (StringUtils.isNotEmpty(dailySaveVo.getTaskIds())) {
            String[] taskArray = dailySaveVo.getTaskIds().split(",");
            for (String hCheckId : taskArray) {
                if (StringUtils.isEmpty(hCheckId)) {
                    continue;
                }
                dailySaveVo.setCheckId(Long.parseLong(hCheckId));
                finaSaveInfo(dailySaveVo, true);
            }
        }
        return dailyCheck;
    }


    @Transactional(rollbackFor = Exception.class)
    public void saveItemListAndContentList(
            RectificationSituationData rectificationSituationData, JgDailyCheck dailyCheck, TcCompany company, String manageStatus) {
        //获取所有已经保存的检查大项
        List<JgDailyStandard> dailyStandardList = jgDailyStandardMapper.selectStandardByCheckId(dailyCheck.getId());
        //批量获取大项
        List<ItemList> itemList = rectificationSituationData.getItemList();
        List<Long> standardIdList = itemList.stream().map(ItemList::getId).collect(Collectors.toList());
        List<JgStandard> itemQueryList = jgStandardMapper.selectBatchIds(standardIdList);
        //获取所有页面传来的检查小项
        List<JgDailyContent> queryDailyContenList = jgDailyContentMapper.selectEntityByDailyCheckId(dailyCheck.getId());
        // 1. 收集需要新增的 dailyStandard
        List<JgDailyStandard> newStandards = new ArrayList<>();
        Map<Long, JgDailyStandard> standardIdToDailyStandard = new HashMap<>(); // 标准ID到DailyStandard的映射

        for (JgStandard standard : itemQueryList) {
            Optional<JgDailyStandard> existing = dailyStandardList.stream()
                    .filter(ds -> Objects.equals(ds.getStandardId(), standard.getId()))
                    .findFirst();

            if (existing.isPresent()) {
                standardIdToDailyStandard.put(standard.getId(), existing.get());
            } else {
                JgDailyStandard dailyStandard = createNewDailyStandard(standard, dailyCheck, company);
                newStandards.add(dailyStandard);
                // 先临时映射，插入后更新ID
                standardIdToDailyStandard.put(standard.getId(), dailyStandard);
            }
        }

        // 2. 批量插入新增的 dailyStandard（获取数据库生成的ID）
        if (!newStandards.isEmpty()) {
            jgDailyStandardMapper.batchInsert(newStandards); // 需确保 MyBatis 配置了 useGeneratedKeys
        }

        // 3. 准备 dailyContent 的批量操作
        List<JgDailyContent> insertContentList = new ArrayList<>();
        List<JgDailyContent> updateContentList = new ArrayList<>();

        // 4. 预构建 existingDailyContent 的映射（dailyStandardId + contentId → DailyContent）
        Map<Long, Map<Long, JgDailyContent>> existingContentMap = new HashMap<>();
        for (JgDailyContent dc : queryDailyContenList) {
            existingContentMap
                    .computeIfAbsent(dc.getDailyStandardId(), k -> new HashMap<>())
                    .put(dc.getContentId(), dc);
        }

        // 5. 遍历处理每个 standard 的 content
        for (JgStandard standard : itemQueryList) {
            JgDailyStandard dailyStandard = standardIdToDailyStandard.get(standard.getId());
            Optional<ItemList> standardParamOp = itemList.stream()
                    .filter(item -> Objects.equals(item.getId(), standard.getId()))
                    .findFirst();
            List<ContentList> contentList = standardParamOp.isPresent() ? standardParamOp.get().getContentList() : new ArrayList<>();
            List<JgCheckContent> contentQueryList = jgCheckContentMapper.selectBatchIds(contentList.stream().map(ContentList::getId).collect(Collectors.toList()));
            for (ContentList content : contentList) {
                // 检查是否已存在 dailyContent
                Map<Long, JgDailyContent> contentIdMap = existingContentMap.getOrDefault(dailyStandard.getId(), new HashMap<>());
                JgDailyContent existingContent = contentIdMap.get(content.getId());
                JgCheckContent contentQuery = contentQueryList.stream().filter(contentQ -> Objects.equals(contentQ.getId(), content.getId())).findFirst().get();
                JgDailyContent dailyContent;
                if (existingContent == null) {
                    // 创建新的 dailyContent
                    dailyContent = new JgDailyContent();
                    dailyContent.setContentId(content.getId());
                    dailyContent.setDailyStandardId(dailyStandard.getId());
                    dailyContent.setCreateTime(new Date());
                    dailyContent.setCreatorId(UserHelper.getUserId());
                    dailyContent.setCreator(UserHelper.getUserInfo().getName());
                    dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dailyContent.setDeleteFlag(0L);
                    dailyContent.setImportentItem(content.getImportentItem());
                    dailyContent.setSerialNum(content.getSerialNum());
                    dailyContent.setMissingItem(content.getMissingItem());
                    dailyContent.setRemark(contentQuery.getRemark());
                    setDailyContent(manageStatus, content, dailyContent, contentQuery);
                    insertContentList.add(dailyContent);
                } else {
                    // 更新现有 dailyContent
                    dailyContent = existingContent;
                    setDailyContent(manageStatus, content, dailyContent, contentQuery);
                    updateContentList.add(dailyContent);
                }

            }
        }

        // 6. 批量保存 dailyContent
        if (!insertContentList.isEmpty()) {
            jgDailyContentMapper.batchInsert(insertContentList);
        }
        if (!updateContentList.isEmpty()) {
            jgDailyContentMapper.batchUpdate(updateContentList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void setDailyContent(String manageStatus, ContentList content, JgDailyContent dailyContent, JgCheckContent contentQuery) {
        dailyContent.setSelection("1".equals(manageStatus) ? "2" : content.getSelection());
        dailyContent.setCheckContent(content.getCheckContent());
        dailyContent.setMissingItemContent(content.getMissingItemContent());
        dailyContent.setProblemContent(content.getProblemContent());
        dailyContent.setProblemContentInput(content.getProblemContentInput());
        dailyContent.setMissingItemContentInput(content.getMissingItemContentInput());
        if ("1".equals(manageStatus)) {
            dailyContent.setScore(contentQuery.getScore());
        } else {
            if ("1".equals(content.getSelection())) {
                dailyContent.setScore(contentQuery.getYesScore());
            } else {
                dailyContent.setScore(contentQuery.getScore());
            }
        }
        if (StringUtils.isNotBlank(content.getProblemFile())
                && !StringUtils.equals(content.getProblemFile(), "undefined")
                && StringUtils.indexOf(content.getProblemFile(), "data:image") >= 0
        ) {
            //上传选择否的时候的图片,如果是data:image开头的才进行上传
            try {
                FileResultEntity filePath = FileUploadUtil.uploadImageBase64Image(content.getProblemFile(), FileUploadEnum.inspect.getPath());
                log.info("新增dailyContent的图片:{}", filePath.getFilePath());
                dailyContent.setProblemFile(filePath.getFilePath());
            } catch (Exception e) {
                log.error("新增dailyContent的图片:{}", e);
            }
        } else {
            dailyContent.setProblemFile(content.getProblemFile());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public JgDailyStandard createNewDailyStandard(JgStandard standard, JgDailyCheck dailyCheck, TcCompany company) {
        JgDailyStandard dailyStandard = new JgDailyStandard();
        dailyStandard.setTemplateId(dailyCheck.getTemplateId());
        dailyStandard.setStandardId(standard.getId());
        dailyStandard.setSupCategory("1");
        dailyStandard.setSupProcess(company.getSupProcess());
        dailyStandard.setSpxsId(standard.getSpxsId());
        dailyStandard.setSupProcess(company.getSupProcess());
        dailyStandard.setCyfwId(standard.getCyfwId());
        dailyStandard.setSpscLbId(standard.getSpscLbId());
        dailyStandard.setSpscLbZlId(standard.getSpscLbZlId());
        dailyStandard.setTsspLbId(standard.getTsspLbId());
        dailyStandard.setTsspLbZlId(standard.getTsspLbZlId());
        dailyStandard.setName(standard.getName());
        dailyStandard.setSerialNum(standard.getSerialNum());
        dailyStandard.setDailyCheckId(dailyCheck.getId());
        dailyStandard.setCreateTime(new Date());
        dailyStandard.setCreatorId(UserHelper.getUserId());
        dailyStandard.setCreator(UserHelper.getUserInfo().getName());
        dailyStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
        dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
        dailyStandard.setDeleteFlag(0L);
        return dailyStandard;
    }

    /*
     *//**
     * 最终保存的时候保存检查内容
     *
     * @param rectificationSituationData
     * @param dailyCheck
     * @param company
     *//*
    public void saveItemListAndContentList(
            JgDailyStandardMapper thjgDailyStandardMapper, JgStandardMapper thjgStandardMapper, JgDailyContentMapper thjgDailyContentMapper,
            JgCheckContentMapper thjgCheckContentMapper,
            RectificationSituationData rectificationSituationData, JgDailyCheck dailyCheck, TcCompany company, String manageStatus ) {
        //获取所有已经保存的检查大项
        List<JgDailyStandard> dailyStandardList = thjgDailyStandardMapper.selectStandardByCheckId(dailyCheck.getId());
        //批量获取大项
        List<ItemList> itemList = rectificationSituationData.getItemList();
        List<Long> standardIdList = itemList.stream().map(ItemList::getId).collect(Collectors.toList());
        List<JgStandard> itemQueryList = thjgStandardMapper.selectBatchIds(standardIdList);
        //获取所有页面传来的检查小项
        List<JgDailyContent> queryDailyContenList = thjgDailyContentMapper.selectEntityByDailyCheckId(dailyCheck.getId());

        for (JgStandard standard : itemQueryList) {
            //获取有没有此项的DailyStandard
            //JgDailyStandard dailyStandard = thjgDailyStandardMapper.selectStandard(standard.getId(), dailyCheck.getId());
            Optional<JgDailyStandard> dailyStandardOp = dailyStandardList.stream().filter(jgDailyStandard -> Objects.equals(jgDailyStandard.getStandardId(), standard.getId())).findFirst();

            JgDailyStandard dailyStandard;
            if (!dailyStandardOp.isPresent()) {
                //创建保存的标准信息
                try {
                    dailyStandard = new JgDailyStandard();
                    dailyStandard.setTemplateId(dailyCheck.getTemplateId());
                    dailyStandard.setStandardId(standard.getId());
                    dailyStandard.setSupCategory("1");
                    dailyStandard.setSupProcess(company.getSupProcess());
                    dailyStandard.setSpxsId(standard.getSpxsId());
                    dailyStandard.setCyfwId(standard.getCyfwId());
                    dailyStandard.setSpscLbId(standard.getSpscLbId());
                    dailyStandard.setSpscLbZlId(standard.getSpscLbZlId());
                    dailyStandard.setTsspLbId(standard.getTsspLbId());
                    dailyStandard.setTsspLbZlId(standard.getTsspLbZlId());
                    dailyStandard.setName(standard.getName());
                    dailyStandard.setSerialNum(standard.getSerialNum());
                    dailyStandard.setDailyCheckId(dailyCheck.getId());
                    dailyStandard.setCreateTime(new Date());
                    dailyStandard.setCreatorId(UserHelper.getUserId());
                    dailyStandard.setCreator(UserHelper.getUserInfo().getName());
                    dailyStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dailyStandard.setDeleteFlag(0L);
                    log.info("新增dailyStandard:{}", dailyStandard);
                    thjgDailyStandardMapper.insert(dailyStandard);
                } catch (Exception e) {
                    log.error("新增dailyStandard:{}", e);
                    throw new RuntimeException("保存检查内容大项失败!");
                }
            } else {
                dailyStandard = dailyStandardOp.get();
            }

            int checkNum = 0;
            ItemList standardParam = itemList.stream().filter(item -> Objects.equals(item.getId(), standard.getId())).findFirst().get();
            List<ContentList> contentList = standardParam.getContentList();
            List<JgDailyContent> insertContentList = new ArrayList<>();
            List<JgDailyContent> updateContentList = new ArrayList<>();
            //查询基础检查内容小项列表
           List<Long> contentIdList = contentList.stream().map(content -> content.getId()).collect(Collectors.toList());
            List<JgCheckContent> queryCheckContentList = thjgCheckContentMapper.selectBatchIds(contentIdList);


            for (ContentList content : contentList) {
                checkNum = checkNum + 1;
                //获取此项检查内容是否已经填写过
                try {
                    Optional<JgDailyContent> dailyContentOp = queryDailyContenList.stream().filter(dailyContent -> Objects.equals(dailyContent.getDailyStandardId(), dailyStandard.getId()) && Objects.equals(dailyContent.getContentId(), content.getId())).findFirst();
                    //JgDailyContent dailyContent = thjgDailyContentMapper.selectByContentAndDailyStandard(content.getId(), dailyStandard.getId(), new ArrayList<>());
                    Optional<JgCheckContent> contentQueryOp = queryCheckContentList.stream().filter(checkContent -> Objects.equals(checkContent.getId(), content.getId())).findFirst();
                    JgDailyContent dailyContent;
                    if (!dailyContentOp.isPresent()) {
                        dailyContent = new JgDailyContent();
                        dailyContent.setContentId(content.getId());
                        dailyContent.setDailyStandardId(dailyStandard.getId());
                        dailyContent.setCreateTime(new Date());
                        dailyContent.setCreatorId(UserHelper.getUserId());
                        dailyContent.setCreator(UserHelper.getUserInfo().getName());
                        dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                        dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                        dailyContent.setDeleteFlag(0L);
                        dailyContent.setCheckContent(content.getCheckContent());
                        dailyContent.setImportentItem(content.getImportentItem());
                        dailyContent.setSerialNum(content.getSerialNum());
                        dailyContent.setMissingItem(content.getMissingItem());
                        dailyContent.setRemark(contentQueryOp.isPresent() ? contentQueryOp.get().getRemark() : "");
                    } else {
                        dailyContent = dailyContentOp.get();
                    }
                    if ("1".equals(manageStatus)) {
                        dailyContent.setScore(contentQueryOp.isPresent() ? contentQueryOp.get().getScore():0);
                    } else {
                        if ("1".equals(content.getSelection())) {
                            dailyContent.setScore(contentQueryOp.isPresent() ? contentQueryOp.get().getYesScore():0);
                        } else {
                            dailyContent.setScore(contentQueryOp.isPresent() ? contentQueryOp.get().getScore():0);
                        }
                    }
                    dailyContent.setSelection("1".equals(manageStatus) ? "2" : content.getSelection());
                    dailyContent.setMissingItemContent(content.getMissingItemContent());
                    dailyContent.setProblemContent(content.getProblemContent());
                    dailyContent.setProblemContentInput(content.getProblemContentInput());
                    dailyContent.setMissingItemContentInput(content.getMissingItemContentInput());
                    if (StringUtils.isNotBlank(content.getProblemFile())
                            && !StringUtils.equals(content.getProblemFile(), "undefined")
                            && StringUtils.indexOf(content.getProblemFile(), "data:image") >= 0
                    ) {
                        //上传选择否的时候的图片,如果是data:image开头的才进行上传
                        FileResultEntity filePath = FileUploadUtil.uploadImageBase64Image(content.getProblemFile(), FileUploadEnum.inspect.getPath());
                        log.info("新增dailyContent的图片:{}", filePath.getFilePath());
                        dailyContent.setProblemFile(filePath.getFilePath());
                    } else {
                        dailyContent.setProblemFile(content.getProblemFile());
                    }
                    if (dailyContent.getId() == null) {
                        log.info("新增dailyContent:{}", dailyContent.toString());
                        insertContentList.add(dailyContent);
                    } else {
                        log.info("修改dailyContent:{}", dailyContent.toString());
                        updateContentList.add(dailyContent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("保存检查内容小项失败!");
                }
            }
            if (insertContentList.size() > 0) {
                thjgDailyContentMapper.batchInsert(insertContentList);
            }
            if (updateContentList.size() > 0) {
                for (JgDailyContent jgDailyContent : updateContentList) {
                    thjgDailyContentMapper.updateById(jgDailyContent);
                }
//                thjgDailyContentMapper.batchUpdate(updateContentList);
            }
        }
    }*/


    /**
     * 保存调查处理
     *
     * @param company    企业信息
     * @param dailyCheck 日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveInvestigation(TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(dailyCheck.getId(), "1");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(dailyCheck.getId());
        investigation.setCheckType("1");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if (investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
        if (!dailyContent.isEmpty()) {
            List<JgInvestigationContent> insertList = new ArrayList<>();

            for (JgDailyContent jgDailyContent : dailyContent) {
                JgInvestigationContent investigationContent = new JgInvestigationContent();
                investigationContent.setInvestigationId(investigation.getId());
                investigationContent.setCheckType("1");
                investigationContent.setCheckContentId(jgDailyContent.getId());
                investigationContent.setCreateTime(new Date());
                investigationContent.setCreatorId(UserHelper.getUserId());
                investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
                investigationContent.setDeleteFlag(0L);
                investigationContent.setSerialNum(jgDailyContent.getStandardNum());
                investigationContent.setStandardName(jgDailyContent.getStandardName());
                investigationContent.setContentNum(jgDailyContent.getSerialNum());
                investigationContent.setCheckContent(jgDailyContent.getCheckContent());
                investigationContent.setSelection(jgDailyContent.getSelection());
                investigationContent.setProblemContent(jgDailyContent.getProblemContent());
                investigationContent.setProblemFile(jgDailyContent.getProblemFile());
                investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
                investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());

                insertList.add(investigationContent);
            }

            // 批量插入
            investigationContentMapper.batchInsert(insertList);
        }


    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     * @param dailyCheck             日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(String rectificationTimeLimit,
                                  TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(dailyCheck.getId(), "1");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(dailyCheck.getId());
        rectification.setCheckType("1");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if (rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }
        //保存整改内容的初始信息
        if (!StringUtils.equals(dailyCheck.getManageStatus(), "1")) {
            //选择的不是经营异常才存储这个问题项
            List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
            if (!dailyContent.isEmpty()) {
                List<JgRectificationContent> insertList = new ArrayList<>();
                for (JgDailyContent jgDailyContent : dailyContent) {
                    JgRectificationContent rectificationContent = new JgRectificationContent();
                    rectificationContent.setRectificationId(rectification.getId());
                    rectificationContent.setCheckType("1");
                    rectificationContent.setCheckContentId(jgDailyContent.getId());
                    rectificationContent.setCreateTime(new Date());
                    rectificationContent.setCreatorId(UserHelper.getUserId());
                    rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                    rectificationContent.setDeleteFlag(0L);
                    rectificationContent.setSerialNum(jgDailyContent.getStandardNum());
                    rectificationContent.setStandardName(jgDailyContent.getStandardName());
                    rectificationContent.setContentNum(jgDailyContent.getSerialNum());
                    rectificationContent.setCheckContent(jgDailyContent.getCheckContent());
                    rectificationContent.setSelection(jgDailyContent.getSelection());
                    rectificationContent.setProblemContent(jgDailyContent.getProblemContent());
                    rectificationContent.setProblemFile(jgDailyContent.getProblemFile());
                    rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                    rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                    rectificationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());

                    insertList.add(rectificationContent);
                }

                // 批量插入
                if (!insertList.isEmpty()) {
                    rectificationContentMapper.batchInsert(insertList);
                }
            }
        }
    }


    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public String uploadResultRecord(Long checkId, MultipartFile imgFile, String type) throws Exception {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        if (imgFile != null && StringUtils.isNoneBlank(imgFile.getOriginalFilename())) {
            FileResultEntity fileResultEntity = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.inspect.getPath());
            if ("1".equals(type)) {
                dailyCheck.setCheckItemTableUrl(fileResultEntity.getFilePath());
            } else if ("2".equals(type)) {
                dailyCheck.setResultRecordUrl(fileResultEntity.getFilePath());
            }
            dailyCheckMapper.updateById(dailyCheck);
            return fileResultEntity.getFilePath();
        }
        return "";

//        dailyCheck.setInformId();
//        dailyCheck.setInformUrl();


    }

    /**
     * 查询检查完成的订单
     *
     * @param checkId 日常检查表id
     * @return
     */
    public Map<String, Object> getCheckResultInfo(Long checkId) {
        Map<String, Object> result = new HashMap<>();
        //检查结果
        Map<String, Object> checkInfo = new HashMap<>();
        //获取和各项，不合格项，合理缺项比例
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        List<Map<String, Object>> contentList = jgDailyContentMapper.selectByDailyCheckId(checkId);
        int hege = 0;
        int buhege = 0;
        int heliquexiang = 0;

        if ("1".equals(dailyCheck.getManageStatus())) {
            JsEntAnomaly entAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), dailyCheck.getType());
            if (entAnomaly != null) {
                checkInfo.put("ECHARTS_NOQUALIFIED", entAnomaly.getCheckNumber());
            }
        }
        // is '选择项：1是、2否、3合理缺项'
        for (Map<String, Object> content : contentList) {
            String selection = content.get("SELECTION") + "";
            switch (selection) {
                case "1":
                    hege++;
                    break;
                case "2":
                    buhege++;
                    break;
                case "3":
                    heliquexiang++;
                    break;
            }
        }
        //处理结果：1通过检查，2责令整改，3调查处理
        checkInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult());
        checkInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        checkInfo.put("CHECK_PERSON1_NAME", dailyCheck.getCheckPerson1Name());
        checkInfo.put("CHECK_PERSON2_NAME", dailyCheck.getCheckPerson2Name());
        checkInfo.put("CHECK_DEPT_NAME", dailyCheck.getDeptName());
        checkInfo.put("CHECK_DATE", dailyCheck.getCheckTime());
        checkInfo.put("TEMPLATE_NAME", dailyCheck.getTemplateName());
        //整改完成时限 获取整改信息
        //List<JgRectification> rectificationList = rectificationMapper.selectByCheckId(dailyCheck.getId(), dailyCheck.getType());
        checkInfo.put("RECTIFICATION_TIME_LIMIT", dailyCheck.getRectificationTimeLimit());
        //其他问题
        checkInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem());
        //监督检查要点表url
        checkInfo.put("CHECK_ITEM_TABLEURL", dailyCheck.getCheckItemTableUrl());
        //结果记录表url
        checkInfo.put("RESULT_RECORD_URL", dailyCheck.getResultRecordUrl());
        result.put("checkInfo", checkInfo);
        //创建日常检查 调试
        // Map<String, Object> supriseInfo = selectSuperviseInfo(checkId, dailyCheck.getCompanyId(), Integer.parseInt(dailyCheck.getCheckNum() + ""));
        Map<String, Object> companyInfo = selectCompanyInfo(checkId, dailyCheck.getCompanyId(), Integer.parseInt(dailyCheck.getCheckNum() + ""));
        //告知页
        JgCheckInform jgCheckInform = jgCheckInformMapper.selectByDailyCheckId(checkId);
        if (jgCheckInform != null) {
            companyInfo.put("INFORM_URL", jgCheckInform.getInformUrl());
        }
        result.put("baseInfo", companyInfo);
        List<Map<String, Object>> standardList = jgDailyStandardMapper.selectDailyCheckId(checkId);
        result.put("standardList", standardList);
        if (contentList.size() == 0) {
            //检查内容没关联上,会显示成全部都是合格的
            checkInfo.put("ECHARTS_QUALIFIED", standardList.size());
        } else {
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", buhege);
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        }
        return result;
    }


    /**
     * 查询检查内容的列表
     *
     * @param dailyStandardId 日常检查表id
     * @return
     */
    public List<Map<String, Object>> getCheckContentList(Long dailyStandardId) {
        return jgDailyContentMapper.selectDailyContentByStandardId(dailyStandardId);
    }

    /**
     * 保存告知单
     *
     * @param checkAddress         检查地址
     * @param checkPerson1Id       第一检查人id
     * @param checkPerson1SignFile 第一检查人签名文件流
     * @param checkPerson2Id       第二检查人id
     * @param checkPerson2SignFile 第二检查人签名文件流
     * @param checkId              检查Id
     * @param companySignFile      企业签名文件流
     * @param isAvoid              是否回避0-否；1-是
     * @param notifyMatters
     * @param taskIds              合并关联任务的id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveCheckInform(Long checkId, Long checkPerson1Id, Long checkPerson2Id, String checkAddress,
                                  String notifyMatters, String isAvoid, String companySignFile, String checkPerson1SignFile,
                                  String checkPerson2SignFile, String informFile, String taskIds) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        if (dailyCheck == null) {
            throw new RuntimeException("请先在检查内容中进行操作");
        }
        JgCheckInform jgCheckInform = jgCheckInformMapper.selectByDailyCheckId(dailyCheck.getId());
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        if (jgCheckInform == null) {
            jgCheckInform = new JgCheckInform();
            jgCheckInform.setCreateTime(new Date());
            jgCheckInform.setDailyCheckId(dailyCheck.getId());
        }
        jgCheckInform.setCompanyName(company.getCompanyName());
        jgCheckInform.setAddress(company.getAddress());
        jgCheckInform.setCheckPerson1Id(checkPerson1Id);
        TsUser user1 = userMapper.selectById(checkPerson1Id);
        jgCheckInform.setCheckPerson1Name(user1.getName());
        jgCheckInform.setCheckPerson2Id(checkPerson2Id);
        TsUser user2 = userMapper.selectById(checkPerson2Id);
        jgCheckInform.setCheckPerson2Name(user2.getName());
        jgCheckInform.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        jgCheckInform.setCheckAddr(checkAddress);
        jgCheckInform.setNotifyMatters(notifyMatters);
        jgCheckInform.setIsAvoid(isAvoid);
        FileResultEntity informFileUrl = null;
        try {
            FileResultEntity companySignUrl = FileUploadUtil.uploadSVGBase64Image(companySignFile, FileUploadEnum.inspect.getPath());
            jgCheckInform.setCompanySign(companySignUrl.getFilePath());
            FileResultEntity checkPerson1SignFileUrl = FileUploadUtil.uploadSVGBase64Image(checkPerson1SignFile, FileUploadEnum.inspect.getPath());
            jgCheckInform.setCheckPerson1Sign(checkPerson1SignFileUrl.getFilePath());
            FileResultEntity checkPerson2SignFileUrl = FileUploadUtil.uploadSVGBase64Image(checkPerson2SignFile, FileUploadEnum.inspect.getPath());
            jgCheckInform.setCheckPerson2Sign(checkPerson2SignFileUrl.getFilePath());
            informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.inspect.getPath());
            jgCheckInform.setInformUrl(informFileUrl.getFilePath());
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败");
        }

        if (jgCheckInform.getId() == null) {
            jgCheckInformMapper.insert(jgCheckInform);
        } else {
            jgCheckInformMapper.updateById(jgCheckInform);
        }
        dailyCheck.setInformId(jgCheckInform.getId());
        dailyCheck.setInformUrl(informFileUrl.getFilePath());
        dailyCheckMapper.updateById(dailyCheck);

        if (StringUtils.isNotEmpty(taskIds)) {
            String[] taskArray = taskIds.split(",");
            for (String taskId : taskArray) {
                if (StringUtils.isEmpty(taskId)) {
                    continue;
                }
                saveCheckInform(Long.parseLong(taskId), checkPerson1Id, checkPerson2Id, checkAddress,
                        notifyMatters, isAvoid, companySignFile, checkPerson1SignFile,
                        checkPerson2SignFile, informFile, "");
            }
        }
        return dailyCheck.getInformUrl();
    }


    /**
     * 查询检查信息
     *
     * @param checkId 检查id
     * @return
     */
    public JgDailyCheck getCheckInfo(Long checkId) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        List<JgDailyContent> dailyContentList = jgDailyContentMapper.selectListByCheckId(checkId);
        List<JgDailyStandard> standardList = new ArrayList<>();
        //筛选出所有standard
        for (JgDailyContent dailyContent : dailyContentList) {
            boolean ex = false;
            for (JgDailyStandard dailyStandard : standardList) {
                if ((dailyStandard.getId() + "").equals(dailyContent.getDailyStandardId() + "")) {
                    ex = true;
                }
            }
            if (!ex) {
                JgDailyStandard dailyStandard = new JgDailyStandard();
                dailyStandard.setName(dailyContent.getStandardName());
                dailyStandard.setSerialNum(dailyContent.getStandardNum());
                dailyStandard.setId(dailyContent.getDailyStandardId());
                standardList.add(dailyStandard);
            }
        }

        for (JgDailyStandard dailyStandard : standardList) {
            for (JgDailyContent dailyContent : dailyContentList) {
                if ((dailyStandard.getId() + "").equals(dailyContent.getDailyStandardId() + "")) {
                    List<JgDailyContent> contentList = dailyStandard.getContentList();
                    if (contentList == null) {
                        contentList = new ArrayList<>();
                    }
                    contentList.add(dailyContent);
                    dailyStandard.setContentList(contentList);
                }
            }
        }
        dailyCheck.setStandardList(standardList);
        return dailyCheck;
    }


    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getResultTable(Long checkId) {
        Map<String, Object> checkInfo = dailyCheckMapper.selectMapById(checkId);
        List<Map<String, Object>> contentList = jgDailyContentMapper.selectByDailyCheckId(checkId);
        Integer contentNum = contentList.size();
        Integer importNum = 0; //重点项
        Integer importProblemNum = 0; //发现问题
        Integer commonlyNum = 0; //一般项
        Integer commonlyProblemNum = 0; //发现问题
        List<String> importNo = new ArrayList<>();//重点项序号
        List<String> importProblemNo = new ArrayList<>();//重点项序号
        List<String> commonlyNo = new ArrayList<>();//一般项序号
        List<String> commonlyProblemNo = new ArrayList<>();//一般项序号
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?");
        for (Map<String, Object> content : contentList) {
            if (content == null) {
                continue;
            }
            //IMPORTENT_ITEM is '重要项：1一般项，2重要项
            //SELECTION is '选择项：1是、2否、3合理缺项
            if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "1")) {
                commonlyNum = commonlyNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    String number = matcher.group();
                    commonlyProblemNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    commonlyNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    commonlyProblemNum = commonlyProblemNum + 1;
                }

            } else if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "2")) {
                importNum = importNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                    String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                    String number = matcher.group();
                    importNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    importNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    importProblemNum = importProblemNum + 1;
                }
            }
        }

        if (checkInfo.get("CHECK_PERSON1_ID") != null && ObjectUtil.isNotEmpty(checkInfo.get("CHECK_PERSON1_ID"))) {
            TsUser user1 = userMapper.selectById(Long.valueOf(checkInfo.get("CHECK_PERSON1_ID").toString()));
            checkInfo.put("enforcementNo1", user1 == null ? "" : user1.getEnforcementNo());
            checkInfo.put("enforcementName1", user1 == null ? "" : user1.getName());
        }
        if (checkInfo.get("CHECK_PERSON2_ID") != null && ObjectUtil.isNotEmpty(checkInfo.get("CHECK_PERSON2_ID"))) {
            TsUser user2 = userMapper.selectById(Long.valueOf(checkInfo.get("CHECK_PERSON2_ID").toString()));
            checkInfo.put("enforcementNo2", user2 == null ? "" : user2.getEnforcementNo());
            checkInfo.put("enforcementName2", user2 == null ? "" : user2.getName());
        }

       /*     QueryWrapper<JgFlightPlanCheck> flightPlanCheckQueryWrapper = new QueryWrapper<>();
            flightPlanCheckQueryWrapper.eq("delete_flag", "0");
            flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
            flightPlanCheckQueryWrapper.eq("company_id", checkInfo.get("COMPANY_ID"));
            flightPlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')", DateUtil.year(new Date()));
            Long flightPlanCheckCount = flightPlanCheckMapper.selectCount(flightPlanCheckQueryWrapper);

            QueryWrapper<JgSchemePlanCheck> schemePlanCheckQueryWrapper = new QueryWrapper<>();
            schemePlanCheckQueryWrapper.eq("delete_flag", "0");
            flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
            schemePlanCheckQueryWrapper.eq("company_id", checkInfo.get("COMPANY_ID"));
            schemePlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')", DateUtil.year(new Date()));
            Long schemePlanCheckCount = schemePlanCheckMapper.selectCount(schemePlanCheckQueryWrapper);*/
/*
            QueryWrapper<JgDailyCheck> jgDailyCheckQueryWrapper = new QueryWrapper<>();
            jgDailyCheckQueryWrapper.eq("delete_flag", "0");
            jgDailyCheckQueryWrapper.eq("CHECK_STAT", "1");
            jgDailyCheckQueryWrapper.eq("company_id", checkInfo.get("COMPANY_ID"));
            jgDailyCheckQueryWrapper.eq("CHECK_YEAR", DateUtil.year(new Date()));
            Long dailyCheckCount = dailyCheckMapper.selectCount(jgDailyCheckQueryWrapper);
            Integer dailyTotalNum = checkInfo.get("DAILY_TOTAL_NUM") == null ? 0 : Integer.parseInt(checkInfo.get("DAILY_TOTAL_NUM") +  "");
            Long checkNum = flightPlanCheckCount + schemePlanCheckCount + dailyCheckCount + 1;*/
        checkInfo.put("CHECK_NUM", (StringUtils.equals(checkInfo.get("TYPE") + "", "1") && StringUtils.equals(checkInfo.get("IS_UNPLANNED") + "", "0")) ? checkInfo.get("CHECK_NUM") : "非计划检查");
        checkInfo.put("isUnplanned", checkInfo.get("IS_UNPLANNED"));
        checkInfo.put("contentNum", contentNum);
        checkInfo.put("importNum", importNum);
        checkInfo.put("importProblemNum", importProblemNum);
        checkInfo.put("commonlyNum", commonlyNum);
        checkInfo.put("commonlyProblemNum", commonlyProblemNum);
        checkInfo.put("importNo", String.join(" ; ", importNo));
        checkInfo.put("importProblemNo", String.join(" ; ", importProblemNo));
        checkInfo.put("commonlyNo", String.join(" ; ", commonlyNo));
        checkInfo.put("commonlyProblemNo", String.join(" ; ", commonlyProblemNo));
        //生成单子编号
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        //检查单今年的流水号
        if (checkInfo.get("RESULT_RECORD_INDEX") == null) {
            //当前单子未生成过.如果第二次保存结果记录表，则直接使用第一次的序号来生成
            JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
            dailyCheck.setResultRecordIndex(resultTableSequence.getTableIndex());//加一并获取
            dailyCheckMapper.updateById(dailyCheck);
        }
        //序号按照6位数在签名补0
        Long index = dailyCheck.getResultRecordIndex();
        if (ObjectUtil.isNotEmpty(checkInfo.get("SUP_PROCESS")) && (StringUtils.equalsAny(checkInfo.get("SUP_PROCESS").toString(), "spxs", "cyfw"))) {
            //经营环节
            TcCompany company = companyMapper.selectEntityById(Long.parseLong(checkInfo.get("COMPANY_ID").toString()));
            String resultCode = SequenceService.generatorResultTableCode(company.getCompanyTypeCode(), index);
            checkInfo.put("resultCode", resultCode);
        } else {
            //特殊食环节 或生产
            String resultCode = SequenceService.generatorProResultTableCode(index);
            checkInfo.put("resultCode", resultCode);
        }
        return checkInfo;
    }


    /**
     * 获取待办的专项检查任务
     *
     * @return
     */
    public List<Map<String, Object>> getSpecialInspectList(Long companyId) {
        CommonSearchEntity params = new CommonSearchEntity();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(UserHelper.getUserInfo().getDataRange());
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        return jgUnplannedCompanyMapper.selectTodoList(params, companyId);
    }

}
